# -*-coding:utf8-*-

import datetime
import time
from nonebot import require, get_driver
from nonebot import get_bot
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event

from HnuclassSystem import hnuclass
from HnuclassSystem import sql
from HnuclassSystem import config

scheduler = require("nonebot_plugin_apscheduler").scheduler

# 晚上十点发送第二天课表
@scheduler.scheduled_job('cron',hour = 22)
async def _():
    
    qqnums = sql.database.selectQQ()
    for qq in qqnums:
        tomorrowClass = sql.database.selectOneDayClass(week = getTomorrowWeek(), day = getTomorrowDay(), qq = qq) # 每一个人的第二天所有课程
        if not tomorrowClass:
            await get_bot().call_api('send_private_msg', user_id = qq, message = '明日无课')
        else:
            for classes in tomorrowClass:
                msg = f'[明日课程]课程名称:{classes[0]}\n教师:{classes[3]}\n节次:第{classes[5]}节'
                await get_bot().call_api('send_private_msg', user_id = qq, message = msg)
                

# 定时任务,用来定时发送课程
@scheduler.scheduled_job('cron',hour = 7, minute = 10)# 每天第一节课
async def _():
    
    allclass = sql.database.selectClass(week = getTodayWeek(), day = getTodayDay(), section = 1)
    for i in allclass:
        '''
        i为元组，内容为：name, week, room, teacher, day, section, qq
        '''
        qq = i[6]
        msg = f'[课程提醒]还有30分钟即将上课,请前往{i[2]}教室上课\n课程名称：{i[0]}\n教师：{i[3]}\n日期:周{i[4]}\n节次:第{i[5]}节'
        try:
            await get_bot().call_api('send_private_msg', user_id = qq, message = msg)
        except :
            print(f'向{qq}发送消息失败')


@scheduler.scheduled_job('cron',hour = 9, minute = 15)# 每天第二节课
async def _():
    
    allclass = sql.database.selectClass(week = getTodayWeek(), day = getTodayDay(), section = 2)
    for i in allclass:
        '''
        i为元组，内容为：name, week, room, teacher, day, section, qq
        '''
        qq = i[6]
        msg = f'[课程提醒]还有30分钟即将上课,请前往{i[2]}教室上课\n课程名称：{i[0]}\n教师：{i[3]}\n日期:周{i[4]}\n节次:第{i[5]}节'
        try:
            await get_bot().call_api('send_private_msg', user_id = qq, message = msg)
        except :
            print(f'向{qq}发送消息失败')


@scheduler.scheduled_job('cron',hour = 14, minute = 0)# 每天第三节课
async def _():
    
    allclass = sql.database.selectClass(week = getTodayWeek(), day = getTodayDay(), section = 3)
    for i in allclass:
        '''
        i为元组，内容为：name, week, room, teacher, riqi, jieci, qq
        '''
        qq = i[6]
        msg = f'[课程提醒]还有30分钟即将上课,请前往{i[2]}教室上课\n课程名称：{i[0]}\n教师：{i[3]}\n日期:周{i[4]}\n节次:第{i[5]}节'
        try:
            await get_bot().call_api('send_private_msg', user_id = qq, message = msg)
        except :
            print(f'向{qq}发送消息失败')


@scheduler.scheduled_job('cron',hour = 16, minute = 5)# 每天第四节课
async def _():
    
    allclass = sql.database.selectClass(week = getTodayWeek(), day = getTodayDay(), section = 4)
    for i in allclass:
        '''
        i为元组，内容为：name, week, room, teacher, riqi, jieci, qq
        '''
        qq = i[6]
        msg = f'[课程提醒]还有30分钟即将上课,请前往{i[2]}教室上课\n课程名称：{i[0]}\n教师：{i[3]}\n日期:周{i[4]}\n节次:第{i[5]}节'
        try:
            await get_bot().call_api('send_private_msg', user_id = qq, message = msg)
        except :
            print(f'向{qq}发送消息失败')


@scheduler.scheduled_job('cron',hour = 18, minute = 40)# 每天第五节课
async def _():
    
    allclass = sql.database.selectClass(week = getTodayWeek(), day = getTodayDay(), section = 5)
    for i in allclass:
        '''
        i为元组，内容为：name, week, room, teacher, riqi, jieci, qq
        '''
        qq = i[6]
        msg = f'[课程提醒]还有30分钟即将上课,请前往{i[2]}教室上课\n课程名称：{i[0]}\n教师：{i[3]}\n日期:周{i[4]}\n节次:第{i[5]}节'
        try:
            await get_bot().call_api('send_private_msg', user_id = qq, message = msg)
        except :
            print(f'向{qq}发送消息失败')



# 添加课表命令
kb = on_command("CreateClass", rule = to_me(), aliases = {'添加课表'}, priority = 4)
@kb.handle()
async def handle_first_receive(bot : Bot, event : Event, state : T_State):
    args = str(event.get_message()).split(' ') # 以空格分开， 返回列表， 0是账号， 1是密码
    stuid, password = args[0], args[1]
    
    try:
        qq = event.get_session_id()
        classes = hnuclass.Hnuclass(stuid, password, qq)
    except hnuclass.AccountError:
        await kb.reject('账号密码错误，或是学校服务器出现问题，请检查')
    
    try:
        # 将账号信息、课程 添加到数据库中
        status = classes.insertAllClass()
        sql.database.insertAccount(stuid, qq)
        if status:
            await get_bot().call_api('send_private_msg', user_id = qq, message = '课表插入成功')
            msg = f'欢迎使用课程提醒功能。可以在网页端查看可以正常提醒的课程，还可以手动添加课程，例如实验课。\n网页端:{config.SERVER_IP}:37373\n账号为学号，密码为对应QQ号'
            await get_bot().call_api('send_private_msg', user_id = qq, message = msg)
    except:
        print('向数据库中添加失败')
        await kb.reject('课表插入失败')
        



# 以下为计算日期的辅助函数
# 计算日期
def Caltime(date1,date2):
    '''
    计算日期
    '''
    date1 = time.strptime(date1,"%Y-%m-%d")
    date2 = time.strptime(date2,"%Y-%m-%d")
    date1=datetime.datetime(date1[0],date1[1],date1[2])
    date2=datetime.datetime(date2[0],date2[1],date2[2])
    return (date2 - date1).days

# 返回今天是第几周
def getTodayWeek():
    '''
    返回今天是第几周,str
    '''
    date1 = config.STARTDATE
    today = datetime.date.today()
    howtodayweek = Caltime(date1,str(today)) // 7 + 1  #得到当前为第几周
    return str(howtodayweek)

# 返回今天是周几
def getTodayDay():
    '''
    返回今天是周几,int
    '''
    today = datetime.date.today()
    return today.isoweekday()

# 返回第二天是第几周
def getTomorrowWeek():
    '''
    返回第二天是第几周,str
    '''
    date1 = config.STARTDATE
    today = datetime.date.today()
    tomorrow = today + datetime.timedelta(days = 1)
    howtomorrowweek = Caltime(date1,str(tomorrow)) // 7 + 1
    return str(howtomorrowweek)

# 返回第二天是周几
def getTomorrowDay():
    '''
    返回第二天是周几,int
    '''
    today = datetime.date.today()
    tomorrow = today.isoweekday() + 1 % 8
    if tomorrow == 8:
        tomorrow = 1
    return tomorrow